package com.zsd.android.rtmpdemo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;

public class PermissionHelper {

    private static volatile PermissionHelper mHelper;
    private Context mContext;

    private PermissionHelper(Context mContext) {
        this.mContext = mContext.getApplicationContext();
    }

    public static PermissionHelper getInstance(Context mContext) {
        PermissionHelper permissionHelper = mHelper;
        if (permissionHelper == null) {
            synchronized (PermissionHelper.class) {
                if (permissionHelper == null) {
                    permissionHelper = new PermissionHelper(mContext);
                    mHelper = permissionHelper;
                }
            }
        }
        return permissionHelper;
    }

    public boolean isPermission(Object object, String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> needPermissions = needPermissions(permissions);
            int size = needPermissions.size();
            if (size > 0) {
                if (object instanceof Activity) {
                    Activity activity = (Activity) object;
                    ActivityCompat.requestPermissions(activity, needPermissions.toArray(new String[size]), requestCode);
                } else if (object instanceof Fragment) {
                    Fragment fragment = (Fragment) object;
                    fragment.requestPermissions(needPermissions.toArray(new String[size]), requestCode);
                }
            }
        }
        return true;
    }

    private ArrayList<String> needPermissions(String... permissions) {
        ArrayList<String> needPermissions = new ArrayList<>();
        for (String permission : permissions) {
            int checkSelfPermission = ContextCompat.checkSelfPermission(mContext, permission);
            if (PackageManager.PERMISSION_DENIED == checkSelfPermission) {
                needPermissions.add(permission);
            }
        }
        return needPermissions;
    }
}
